const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session');
const bodyParser = require('body-parser');

const indexRouter = require('./routes/index');
const userRouter = require('./routes/user');
const proRouter = require('./routes/pro');
const orderRouter = require('./routes/order');
const messageRouter = require('./routes/message');
const cartRouter = require('./routes/cart');
const bannerRouter = require('./routes/banner');
const activityRouter = require('./routes/activity');

// Api 接口
const proApiRouter = require('./api/pro');
const bannerApiRouter = require('./api/banner');
const commentApi = require('./api/comment');
const orderApiRouter = require('./api/order');
const userApiRouter = require('./api/user');
const cartApiRouter = require('./api/cart');
const addressApiRouter = require('./api/address');
const searchApiRouter = require('./api/search');
const payApiRouter = require('./api/pay');

const app = express();

// // 自定义中间件 ---  解决跨域问题
// var allowCrossDomain = (req, res, next) => {
//   // get req.query post req.body
//   // res
//   // 所有接口均可以访问服务器
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header('Access-Control-Allow-Headers', '*')
//   next()
// }
// // 使用自定义跨域中间件
// app.use(allowCrossDomain)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// 解决post提交图片过大问题
app.use(bodyParser.json({ limit: '50mb' })); // for parsing application/json
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); // for parsing application/x-www-form-urlencoded
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: "nihao", //加密session，随便写 
  // cookie: { maxAge: 5 * 1000 }, //设置过期时间 --- 5s 
  cookie: { maxAge: 60 * 1000 * 30 }, //设置过期时间 --- 半小时 
  resave: true, //强制保存session 默认为 true，建议设置成false 
  saveUninitialized: false ////强制将未初始化的session存储 默认为true，建议设置成true 
}));

// API接口
app.use("/api/pro", proApiRouter);
app.use("/api/banner", bannerApiRouter);
app.use("/api/order", orderApiRouter);
app.use("/api/comment", commentApi);
app.use("/api/user", userApiRouter);
app.use("/api/cart", cartApiRouter);
app.use("/api/address", addressApiRouter);
app.use("/api/search", searchApiRouter);
app.use("/api/pay", payApiRouter);

// 路由登录验证
app.all("*", (req, res, next) => {
  // 访问所有路由地址（除了/login 和 /loginAction）先进行验证是否登录
  if (req.url === "/login" || req.url === "/loginAction") {
    next();
  } else {
    if (req.session.loginStart === true) {
      next();
    } else {
      res.redirect("/login");
    }
  }
})

app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/pro', proRouter);
app.use('/order', orderRouter);
app.use('/message', messageRouter);
app.use('/cart', cartRouter);
app.use('/banner', bannerRouter);
app.use('/activity', activityRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
